import 'dart:core';
import 'dart:convert';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:sp_util/sp_util.dart';
import 'package:video_player/video_player.dart';
import 'package:yp/Xwidgets/bottom_sheet.dart';
import 'package:yp/config/index.dart';
import 'package:yp/services/api.dart';
import 'package:yp/util/util.dart';
import 'package:yp/utils/util.dart';
import 'package:yp/utils/videoplayer/video_player_plus.dart';
import 'package:yp/widgets/button_widget.dart';
import 'package:yp/widgets/cache_image.dart';
import 'package:yp/widgets/navigation_bar.dart';
import 'package:html/dom.dart' as dom;
import 'package:fluwx/fluwx.dart' as fluwx;
import '../../router.dart';

import 'package:yp/pages/address_selector/address_model.dart';

class EventDetail extends StatefulWidget {
  const EventDetail({Key key}) : super(key: key);

  @override
  _EventDetailState createState() => _EventDetailState();
}

class _EventDetailState extends State<EventDetail>
    with SingleTickerProviderStateMixin {
  // AnimationController _controller;
  // VideoPlayerController _controller1;
  bool _like = false;
  Map arguments;
  Map content_detail;
  Map spec_item_detail;
  var videourl = '';
  var mainImageurl = '';
  Map coupon;
  bool showTip = false;
  List newContentDetails = [];
  List<Widget> newContentRows = [];
  getInfo() {
    var params2 = {
      'series': arguments['series'],
      // 'usr_num_id': SpUtil.getInt('empeNumId'),
      // 'access_token': SpUtil.getString('token'),
    };

    Api.detailquery(params2).listen((event) {
      if (event['code'] == 0) {
        if (event['content_detail'] != null) {
          setState(() {
            content_detail = event['content_detail'];
            try {
              newContentDetails = json.decode(content_detail['content_text']);
              newContentDetails.forEach((e) {
                setState(() {
                  newContentRows.add(RowDetail(HtmlRow: e));
                });
              });
            } catch (e) {
              toast('内容加载异常');
            }
            videourl = content_detail['video_url'];
            mainImageurl = content_detail['img_url'];
            // _controller1 = VideoPlayerController.network(content_detail['video_url'])
            //   ..initialize().then((_) {
            //     // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
            //     setState(() {});
            //   });
          });
        }
        // toast("修改成功");
      }
    });
  }

  getcoupon(coupon_num_id) {
    var params = {
      // "usr_num_id": SpUtil.getInt('empeNumId'),
      // 'access_token': SpUtil.getString('token'),
      "activityids": [coupon_num_id] //全规则编号(多个)
    };

    Api.couponclaim(params).listen((event) {
      if (event["code"] == 0) {
        setState(() {
          if (event["card_tickets"] != null &&
              event["card_tickets"].length > 0) {
            coupon = event["card_tickets"][0];
          }
        });
      }
    });
  }

  getshop(itemNumId) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "channel_num_id": 99,
        "use_platform": 2,
        "style_num_id": content_detail['item_num_id'],
        // "shop_id": SpUtil.getInt('storeShopNum'),
        "shop_id": SpUtil.getInt('storeShopNum') != null &&
                SpUtil.getInt('storeShopNum') != 0
            ? SpUtil.getInt('storeShopNum').toString()
            : 102002001,
        "item_num_id": itemNumId,
        // "access_token": SpUtil.getString('token'),

        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        // "user_num_id": SpUtil.getInt('empeNumId'),
        'customer_type': 3,
      };

      Api.goodsDetail(params).listen((event) {
        if (event["code"] == 0) {
          setState(() {
            spec_item_detail = event["spec_item_detail"];
          });
        }
      });
    });
  }

  swichAct(type) {
    Map data;
    if (type == 1) {
      data = {'name': '拼团活动', 'router': RouteConfig.collage};
    }
    if (type == 2) {
      data = {'name': '秒杀活动', 'router': RouteConfig.seckillHome};
    }
    return data;
  }

  dzfun(Map info) {
    var params2 = {
      'flag': info['is_like'] == 1 ? -1 : 1,
      'content_series': info['series'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentlikes(params2).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          info['is_like'] == 1 ? info['likes_num']-- : info['likes_num']++;
          info['is_like'] == 1 ? info['is_like'] = -1 : info['is_like'] = 1;
        });
        // toast("修改成功");
      }
    });
  }

  dyfun(Map info) {
    var params2 = {
      'flag': info['is_collection'] == 1 ? -1 : 1,
      'content_series': info['series'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentcollec(params2).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          info['is_collection'] == 1
              ? info['is_collection'] = -1
              : info['is_collection'] = 1;
        });
        // toast("修改成功");
      }
    });
  }

  getconntype(type_id) {
    var name = '';
    if (type_id == 0) {
      name = '折扣券';
    }
    if (type_id == 1) {
      name = '现金券';
    }
    if (type_id == 2) {
      name = '免邮券';
    }
    if (type_id == 8) {
      name = '兑换券';
    }
    return name;
  }

  @override
  void initState() {
    if (Get.arguments == null) {
      print('新arguments');
      arguments = {
        'is_like': int.parse(getQueryVariable('is_like')),
        'likes_num': int.parse(getQueryVariable('likes_num')),
        'view_num': getQueryVariable('view_num'),
        'is_collection': int.parse(getQueryVariable('is_collection')),
        'series': int.parse(getQueryVariable('series'))
      };
      // if (SpUtil.getInt('empeNumId') == 0 || SpUtil.getInt('empeNumId') == null) {
      //   Get.offAllNamed(RouteConfig.mallLogin, arguments: arguments);
      //   return;
      // }
      print(arguments);
    } else {
      print('这是传过来的值');
      arguments = Get.arguments;
      // if (SpUtil.getInt('empeNumId') == 0 || SpUtil.getInt('empeNumId') == null) {
      //   Get.offAllNamed(RouteConfig.mallLogin, arguments: arguments);
      //   return;
      // }
    }

    getInfo();
    super.initState();
    // _controller = AnimationController(vsync: this);
    // _controller1 = VideoPlayerController.network('')
    //   ..initialize().then((_) {
    //     // Ensure the first frame is shown after the video is initialized, even before the play button has been pressed.
    //     setState(() {});
    //   });
  }

  @override
  void dispose() {
    // _controller1.dispose();
    super.dispose();
    // _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(
        BoxConstraints(
            maxWidth: MediaQuery.of(context).size.width,
            maxHeight: MediaQuery.of(context).size.height),
        designSize: Size(750, 1334),
        orientation: Orientation.portrait);
    return Stack(
      children: [
        Scaffold(
            appBar: YPNavigationBar(
              '发现详情',
              onPressed: () {
                // Get.offAllNamed(RouteConfig.discover);
                Get.back();
              },
              showBack: kIsWeb ? false : true,
            ),
            body: Padding(
              padding: EdgeInsets.fromLTRB(24.w, 24.w, 24.w,
                  MediaQuery.of(context).padding.bottom + 100.w),
              child: CustomScrollView(slivers: [
                SliverToBoxAdapter(
                    child: content_detail != null
                        ? Column(children: [
                            _header(),
                            _mainImage(),
                            videourl.length > 0 ? _video() : Container(),
                            //_html(), coupon != null ? _coupon() : Container(), _collage(), spec_item_detail != null ? _goods() : Container(),
                            Column(
                              children: newContentRows,
                            ),
                            SizedBox(height: 40.w)
                          ])
                        : Container())
              ]),
            ),
            floatingActionButton: _bottom(),
            floatingActionButtonLocation:
                FloatingActionButtonLocation.centerDocked,
            backgroundColor: EsColors.White),
        if (showTip)
          InkWell(
            onTap: () {
              setState(() {
                showTip = !showTip;
              });
            },
            child: Container(
              color: Colors.black45.withOpacity(.75),
              child: Center(
                  child: Text(
                "请点击右上角的'...'\n然后选择在浏览器打开",
                style: TextStyle(
                  color: Colors.white,
                  fontSize: 18,
                ),
                textAlign: TextAlign.center,
              )),
            ),
          ),
      ],
    );
  }

  /// 标题 来源 时间
  Widget _header() {
    return Column(children: [
      Text(content_detail['title'],
          style: TextStyle(
              color: EsColors.Title,
              fontSize: EsSizes.LG * 2.sp,
              fontWeight: EsFontWeights.Normal)),
      SizedBox(height: 20.w),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(content_detail['sub_title'],
              style: TextStyle(
                  color: EsColors.Content,
                  fontSize: EsSizes.SM * 2.sp,
                  fontWeight: EsFontWeights.Normal)),
        ],
      ),
      SizedBox(height: 5.w),
      Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text("发布时间:${content_detail['create_dtme']}",
              style: TextStyle(
                  color: EsColors.Content,
                  fontSize: EsSizes.SM * 2.sp,
                  fontWeight: EsFontWeights.Normal)),
        ],
      ),
      SizedBox(height: 20.w)
    ]);
  }

  /// 播放器
  Widget _video() {
    return Visibility(
      visible: videourl.length > 0,
      child: Stack(
        children: [
          Container(
              width: double.infinity,
              height: MediaQuery.of(context).size.width * 0.55,
              color: EsColors.BackGround,
              child: VideoPlayerPlus(
                VideoPlayerController.network(videourl),
              )),
          // Positioned(
          //     left: 16.w,
          //     bottom: 20.w,
          //     child: EsIconButton(
          //       Icon(
          //         _controller1.value.isPlaying ? Icons.pause : Icons.play_arrow,
          //         size: 60.w,
          //       ),
          //       onTap: () {
          //         setState(() {
          //           _controller1.value.isPlaying ? _controller1.pause() : _controller1.play();
          //         });
          //       },
          //     ))
        ],
      ),
    );
  }

  Widget _mainImage() {
    if (mainImageurl == '' || mainImageurl == null) {
      return Container();
    } else {
      return Image.network(mainImageurl);
    }
  }

  /// 富文本
  Widget _html() {
    return Html(data: content_detail['content_text']);
  }

  Widget _bottom() {
    return Container(
      decoration: BoxDecoration(
          color: EsColors.White,
          borderRadius: BorderRadius.circular(8.w),
          boxShadow: [
            BoxShadow(
              color: Color.fromRGBO(71, 88, 191, 0.12),
              blurRadius: 5.0,
              offset: Offset(0, -5),
              spreadRadius: 1.0,
            )
          ]),
      padding: EdgeInsets.fromLTRB(16, 12, 16, 12),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        EsIconButton(
          Icon(
              arguments['is_like'] == 1
                  ? Icons.favorite
                  : Icons.favorite_border,
              color: arguments['is_like'] == 1
                  ? EsColors.Primary
                  : EsColors.ContentSecondary,
              size: 50.w),
          onTap: () {
            if (kIsWeb) {
              /// 跳转到app失败 进入下载页或者提示系统浏览器打开
              Future.delayed(Duration(seconds: 1), () {
                if (isWechat()) {
                  // toast('请在系统浏览器打开本页面');
                  // Navigator.of(context).pop();
                  setState(() {
                    showTip = true;
                  });
                } else {
                  /// 进入下载页
                  webpay(Config.WEB_DOWN_URL +
                      "download.html?is_like=" +
                      arguments['is_like'].toString() +
                      '&likes_num=' +
                      arguments['likes_num'].toString() +
                      '&view_num=' +
                      arguments['view_num'].toString() +
                      '&is_collection=' +
                      arguments['is_collection'].toString() +
                      '&series=' +
                      arguments['series'].toString());
                }
              });
              webpay("yinpinhui://zrhsh.com/app?is_like=" +
                  arguments['is_like'].toString() +
                  '&likes_num=' +
                  arguments['likes_num'].toString() +
                  '&view_num=' +
                  arguments['view_num'].toString() +
                  '&is_collection=' +
                  arguments['is_collection'].toString() +
                  '&series=' +
                  arguments['series'].toString());
            } else {
              dzfun(arguments);
            }
          },
        ),
        Text('浏览${arguments['view_num'].toString()}人',
            style: TextStyle(
                color: EsColors.Content,
                fontSize: EsSizes.MD * 2.sp,
                fontWeight: EsFontWeights.Normal)),
        kIsWeb != true
            ? EsIconButton(
                Icon(Icons.share, color: EsColors.ContentSecondary, size: 48.w),
                onTap: () {
                  var info = jsonEncode(arguments);
                  var shareUrl;
                  //shareUrl =     Config.WEB_URL + 'event_detail?is_like=' + arguments['is_like'].toString() + '&likes_num=' + arguments['likes_num'].toString() + '&view_num=' + arguments['view_num'].toString() + '&is_collection=' + arguments['is_collection'].toString() + '&series=' + arguments['series'].toString(),,
                  shareUrl = Config.H5_URL +
                      '&isGofindDetail=true&id=' + content_detail['series'].toString() +'&is_like=' + arguments['is_like'].toString() + '&likes_num=' + arguments['likes_num'].toString() + '&view_num=' + arguments['view_num'].toString() + '&is_collection=' + arguments['is_collection'].toString() + '&series=' + arguments['series'].toString() ;

                  YpBottomSheet.showShareGift(context,
                      (selectIndex, selectString, {info, list}) {
                    if (selectIndex == 0) {
                      var model = fluwx.WeChatShareWebPageModel(
                        shareUrl,
                        title: content_detail['title'],
                        description: content_detail['sub_title'],
                        thumbnail: fluwx.WeChatImage.asset(
                            'assets/images/ic_launcher.png',
                            suffix: '.png'),
                        scene: fluwx.WeChatScene.SESSION,
                      );
                      fluwx.shareToWeChat(model);
                    } else {
                      var model = fluwx.WeChatShareWebPageModel(
                        shareUrl,
                        title: content_detail['title'],
                        description: content_detail['sub_title'],
                        thumbnail: fluwx.WeChatImage.asset(
                            'assets/images/ic_launcher.png',
                            suffix: '.png'),
                        scene: fluwx.WeChatScene.TIMELINE,
                      );
                      fluwx.shareToWeChat(model);
                    }
                  }, title: '');

                  // var model = new WeChatShareMiniProgramModel(
                  //              path: '/pages/index,
                  //              webPageUrl: 'www.baidu.com',
                  //              userName: Config.MINI_ACCOUNT,
                  //              // mini  ProgramType: WXMiniProgramType.RELEASE,
                  //              miniProgramType: WXMiniProgramType.RELEASE,
                  //              title: item.itemName,
                  //              description: item.itemName,
                  //              thumbnail: WeChatImage.network(
                  //                "${item.imageSrc}",
                  //              ),
                  //            );
                  //            fluwx.shareToWeChat(model);
                  print('立即邀请');
                },
              )
            : SizedBox(
                width: 48.w,
              ),
        EsOutLineButton(arguments['is_collection'] == 1 ? '取消订阅' : '+ 订阅',
            borderColor: arguments['is_collection'] == 1
                ? Colors.grey
                : EsColors.Primary,
            textColor: arguments['is_collection'] == 1
                ? Colors.grey
                : EsColors.Primary,
            padding: EdgeInsets.symmetric(horizontal: 24.w, vertical: 6.w),
            onTap: () {
          print('订阅');
          if (kIsWeb) {
            /// 跳转到app失败 进入下载页或者提示系统浏览器打开
            Future.delayed(Duration(seconds: 1), () {
              if (isWechat()) {
                // toast('请在系统浏览器打开本页面');
                // Navigator.of(context).pop();
                setState(() {
                  showTip = true;
                });
              } else {
                /// 进入下载页
                webpay(Config.WEB_DOWN_URL +
                    "download.html?is_like=" +
                    arguments['is_like'].toString() +
                    '&likes_num=' +
                    arguments['likes_num'].toString() +
                    '&view_num=' +
                    arguments['view_num'].toString() +
                    '&is_collection=' +
                    arguments['is_collection'].toString() +
                    '&series=' +
                    arguments['series'].toString());
              }
            });
            webpay("yinpinhui://zrhsh.com/app?is_like=" +
                arguments['is_like'].toString() +
                '&likes_num=' +
                arguments['likes_num'].toString() +
                '&view_num=' +
                arguments['view_num'].toString() +
                '&is_collection=' +
                arguments['is_collection'].toString() +
                '&series=' +
                arguments['series'].toString());
          } else {
            dyfun(arguments);
          }
        }),
      ]),
    );
  }

  /// 优惠券
  Widget _coupon() {
    return GestureDetector(
      onTap: () {
        if (kIsWeb) {
          /// 跳转到app失败 进入下载页或者提示系统浏览器打开
          Future.delayed(Duration(seconds: 1), () {
            if (isWechat()) {
              // toast('请在系统浏览器打开本页面');
              // Navigator.of(context).pop();
              setState(() {
                showTip = true;
              });
            } else {
              /// 进入下载页
              webpay(Config.WEB_DOWN_URL +
                  "download.html?is_like=" +
                  arguments['is_like'].toString() +
                  '&likes_num=' +
                  arguments['likes_num'].toString() +
                  '&view_num=' +
                  arguments['view_num'].toString() +
                  '&is_collection=' +
                  arguments['is_collection'].toString() +
                  '&series=' +
                  arguments['series'].toString());
            }
          });
          webpay("yinpinhui://zrhsh.com/app?is_like=" +
              arguments['is_like'].toString() +
              '&likes_num=' +
              arguments['likes_num'].toString() +
              '&view_num=' +
              arguments['view_num'].toString() +
              '&is_collection=' +
              arguments['is_collection'].toString() +
              '&series=' +
              arguments['series'].toString());
        } else {
          if (spec_item_detail['store'] > 0) {
            Get.offNamed(RouteConfig.collectCouponsCentre);
          }
        }
      },
      child: Visibility(
        visible: coupon != null,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: double.infinity,
              height: 200.w,
              child: Row(children: [
                Expanded(
                  flex: 1,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      RichText(
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          text: TextSpan(children: [
                            TextSpan(
                                text: getconntype(coupon['type_id']),
                                style: TextStyle(
                                    fontSize: 40.w,
                                    fontWeight: EsFontWeights.SemiBold,
                                    color: EsColors.White))
                          ])),
                      // Container(
                      //   padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                      //   decoration: BoxDecoration(color: Color(0xffd32f14), borderRadius: BorderRadius.circular(8)),
                      //   child: Text(
                      //     '满49可用',
                      //     maxLines: 1,
                      //     overflow: TextOverflow.ellipsis,
                      //     style: TextStyle(color: EsColors.White, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal),
                      //   ),
                      // )
                    ],
                  ),
                ),
                Expanded(
                    flex: 2,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          coupon['title'],
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: EsColors.Money,
                              fontSize: EsSizes.MD,
                              fontWeight: EsFontWeights.SemiBold),
                        ),
                        SizedBox(height: 14),
                        Text(
                          getyearDayFromTimestamp(coupon['use_begin_date']) +
                              '-' +
                              getyearDayFromTimestamp(coupon['use_begin_end']),
                          style: TextStyle(
                              color: EsColors.ContentSecondary,
                              fontSize: EsSizes.XS,
                              fontWeight: EsFontWeights.Normal),
                        ),
                      ],
                    ))
              ]),
              decoration: BoxDecoration(
                  image: DecorationImage(
                      fit: BoxFit.fill,
                      image: AssetImage('assets/images/give_coupons_bg.png'))),
            ),
          ],
        ),
      ),
    );
  }

  ///  拼团活动？？
  Widget _collage() {
    return swichAct(content_detail['activity_type']) != null
        ? GestureDetector(
            onTap: () {
              if (kIsWeb) {
                /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                Future.delayed(Duration(seconds: 1), () {
                  if (isWechat()) {
                    // toast('请在系统浏览器打开本页面');
                    // Navigator.of(context).pop();
                    setState(() {
                      showTip = true;
                    });
                  } else {
                    /// 进入下载页
                    webpay(Config.WEB_DOWN_URL +
                        "download.html?is_like=" +
                        arguments['is_like'].toString() +
                        '&likes_num=' +
                        arguments['likes_num'].toString() +
                        '&view_num=' +
                        arguments['view_num'].toString() +
                        '&is_collection=' +
                        arguments['is_collection'].toString() +
                        '&series=' +
                        arguments['series'].toString());
                  }
                });
                webpay("yinpinhui://zrhsh.com/app?is_like=" +
                    arguments['is_like'].toString() +
                    '&likes_num=' +
                    arguments['likes_num'].toString() +
                    '&view_num=' +
                    arguments['view_num'].toString() +
                    '&is_collection=' +
                    arguments['is_collection'].toString() +
                    '&series=' +
                    arguments['series'].toString());
              } else {
                if (spec_item_detail['store'] > 0) {
                  Get.toNamed(
                      swichAct(content_detail['activity_type'])['router']);
                }
              }
            },
            child: Container(
              margin: EdgeInsets.only(top: 20.w),
              decoration: BoxDecoration(
                  color: EsColors.Pink,
                  borderRadius:
                      const BorderRadius.all(const Radius.circular(6.0))),
              height: 200.w,
              child: Center(
                child: Text(
                  swichAct(content_detail['activity_type'])['name'],
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          )
        : Container();
  }

  /// 商品
  Widget _goods() {
    return Container(
      margin: EdgeInsets.fromLTRB(20.w, 26.w, 20.w, 0),
      padding: EdgeInsets.all(20.w),
      decoration: EsDecoration.BoxShadowRadius6,
      alignment: Alignment.center,
      child: Row(
        children: [
          GestureDetector(
              onTap: () {
                var itemNumId = spec_item_detail['item_num_id'].toString();
                var styleNumId = spec_item_detail['style_num_id'].toString();
                var shopId = '102002001';
                var ecStyleNumId =
                    spec_item_detail['ec_style_num_id'].toString();
                var typeIndex = spec_item_detail['is_pre_sale'] != null
                    ? spec_item_detail['is_pre_sale']
                    : 0;
                var data = {
                  'itemNumId': itemNumId,
                  'styleNumId': styleNumId,
                  // 'shopId': SpUtil.getInt('storeShopNum').toString(),
                  'shopId': shopId,
                  'ecStyleNumId': ecStyleNumId,
                  'typeIndex': typeIndex,
                };
                Get.toNamed(
                    RouteConfig.goodsDetail +
                        '?itemNumId=$itemNumId&styleNumId=$styleNumId&shopId=$shopId&ecStyleNumId=$ecStyleNumId&typeIndex=$typeIndex',
                    arguments: data);
              },
              child: CachedImage(
                  width: 200.w,
                  height: 200.w,
                  path: '${spec_item_detail['image_default_id']}')),
          SizedBox(width: 24.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                    constraints: BoxConstraints(minHeight: 140.w),
                    child: Text(content_detail['item_name'],
                        style: TextStyle(
                            color: EsColors.Title,
                            fontSize: EsSizes.SM * 2.sp,
                            fontWeight: EsFontWeights.Normal))),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        // Text('已抢98765件',
                        //     style: TextStyle(
                        //         color: EsColors.ContentSecondary,
                        //         fontSize: EsSizes.XS * 2.sp,
                        //         fontWeight: EsFontWeights.Normal)),
                        Row(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 4.w, right: 10.w),
                              child: Text('￥${spec_item_detail['price']}',
                                  style: TextStyle(
                                      color: EsColors.Primary,
                                      fontSize: 30.sp,
                                      fontWeight: EsFontWeights.Normal)),
                            ),
                            Text('￥${spec_item_detail['mkt_price']}',
                                style: TextStyle(
                                    decoration: TextDecoration.lineThrough,
                                    color: EsColors.ContentSecondary,
                                    fontSize: 20.sp,
                                    fontWeight: EsFontWeights.Normal)),
                          ],
                        ),
                      ],
                    ),
                    Expanded(child: SizedBox()),
                    GestureDetector(
                      onTap: () {
                        if (kIsWeb) {
                          /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                          Future.delayed(Duration(seconds: 1), () {
                            if (isWechat()) {
                              // toast('请在系统浏览器打开本页面');
                              // Navigator.of(context).pop();
                              setState(() {
                                showTip = true;
                              });
                            } else {
                              /// 进入下载页
                              webpay(Config.WEB_DOWN_URL +
                                  "download.html?is_like=" +
                                  arguments['is_like'].toString() +
                                  '&likes_num=' +
                                  arguments['likes_num'].toString() +
                                  '&view_num=' +
                                  arguments['view_num'].toString() +
                                  '&is_collection=' +
                                  arguments['is_collection'].toString() +
                                  '&series=' +
                                  arguments['series'].toString());
                            }
                          });
                          webpay("yinpinhui://zrhsh.com/app?is_like=" +
                              arguments['is_like'].toString() +
                              '&likes_num=' +
                              arguments['likes_num'].toString() +
                              '&view_num=' +
                              arguments['view_num'].toString() +
                              '&is_collection=' +
                              arguments['is_collection'].toString() +
                              '&series=' +
                              arguments['series'].toString());
                        } else {
                          if (spec_item_detail['store'] > 0) {
                            Get.toNamed(RouteConfig.settleAccounts, arguments: {
                              // 'shop_id': SpUtil.getInt('storeShopNum'),
                              'shop_id': SpUtil.getInt('storeShopNum'),
                              "item_num_id": content_detail['item_num_id'],
                              "style_num_id": content_detail['item_num_id'],
                              "ec_style_num_id": content_detail['item_num_id'],
                              'shopnum': 1
                            });
                          }
                        }

                        print('马上抢');
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            vertical: 10.w, horizontal: 24.w),
                        child: Text(
                            spec_item_detail['store'] > 0 ? '马上抢' : '已售馨',
                            style: TextStyle(
                                color: EsColors.White,
                                fontSize: EsSizes.MD * 2.sp,
                                fontWeight: EsFontWeights.Medium)),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            ///渐变色
                            colors: [Color(0xffea5504), Color(0xffffbd00)],
                          ),
                          borderRadius: BorderRadius.all(Radius.circular(30.w)),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}

class RowDetail extends StatefulWidget {
  const RowDetail({Key key, @required this.HtmlRow}) : super(key: key);

  final Map HtmlRow;

  @override
  _RowDetailState createState() => _RowDetailState();
}

class _RowDetailState extends State<RowDetail> {
  // AnimationController _controller;
  // VideoPlayerController _controller1;
  bool _like = false;
  Map arguments;
  Map content_detail;
  Map spec_item_detail;
  var videourl = '';
  Map coupon;
  bool showTip = false;

  getInfo() {
    if (content_detail['hasBindingGoods'] == true) {
      if (content_detail['bindingGoods']['goods'] != null) {
        getshop(content_detail['bindingGoods']['goods']['style_num_id']);
      }
      if (content_detail['bindingGoods']['coupon'] != null) {
        getcoupon(content_detail['bindingGoods']['coupon']['series']);
      }
    }
  }

  getcoupon(coupon_num_id) {
    var params = {
      // "usr_num_id": SpUtil.getInt('empeNumId'),
      // 'access_token': SpUtil.getString('token'),
      "activityids": [coupon_num_id] //全规则编号(多个)
    };

    Api.couponclaim(params).listen((event) {
      if (event["code"] == 0) {
        setState(() {
          if (event["card_tickets"] != null &&
              event["card_tickets"].length > 0) {
            setState(() {
              coupon = event["card_tickets"][0];
            });
          }
        });
      }
    });
  }

  getshop(itemNumId) {
    getCurrentLocationInfo(success: (data) {
      var addressInfo = data['addressInfo'];
      var params = {
        "channel_num_id": 99,
        "use_platform": 2,
        "style_num_id": itemNumId,
        // "shop_id": SpUtil.getInt('storeShopNum'),
        "shop_id": SpUtil.getInt('storeShopNum') != null &&
                SpUtil.getInt('storeShopNum') != 0
            ? SpUtil.getInt('storeShopNum').toString()
            : 102002001,
        "item_num_id": itemNumId,
        // "access_token": SpUtil.getString('token'),
        "prv_num_id": addressInfo['prv_num_id'],
        "city_num_id": addressInfo['city_num_id'],
        "city_area_num_id": addressInfo['city_area_num_id'],
        "town_num_id": addressInfo['town_num_id'],
        "maplocation_x": addressInfo['maplocation_x'],
        "maplocation_y": addressInfo['maplocation_y'],
        // "user_num_id": SpUtil.getInt('empeNumId'),
        'customer_type': 3,
      };

      Api.goodsDetail(params).listen((event) {
        if (event["code"] == 0) {
          setState(() {
            spec_item_detail = event["spec_item_detail"];
          });
        }
      });
    });
  }

  swichAct(type) {
    Map data;
    if (type == 1) {
      data = {'name': '拼团活动', 'router': RouteConfig.collage};
    }
    if (type == 2) {
      data = {'name': '秒杀活动', 'router': RouteConfig.seckillHome};
    }
    return data;
  }

  dzfun(Map info) {
    var params2 = {
      'flag': info['is_like'] == 1 ? -1 : 1,
      'content_series': info['series'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentlikes(params2).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          info['is_like'] == 1 ? info['likes_num']-- : info['likes_num']++;
          info['is_like'] == 1 ? info['is_like'] = -1 : info['is_like'] = 1;
        });
        // toast("修改成功");
      }
    });
  }

  dyfun(Map info) {
    var params2 = {
      'flag': info['is_collection'] == 1 ? -1 : 1,
      'content_series': info['series'],
      'usr_num_id': SpUtil.getInt('empeNumId'),
      'access_token': SpUtil.getString('token'),
    };

    Api.contentcollec(params2).listen((event) {
      if (event['code'] == 0) {
        setState(() {
          info['is_collection'] == 1
              ? info['is_collection'] = -1
              : info['is_collection'] = 1;
        });
        // toast("修改成功");
      }
    });
  }

  getconntype(type_id) {
    var name = '';
    if (type_id == 0) {
      name = '折扣券';
    }
    if (type_id == 1) {
      name = '现金券';
    }
    if (type_id == 2) {
      name = '免邮券';
    }
    if (type_id == 8) {
      name = '兑换券';
    }
    return name;
  }

  @override
  void initState() {
    content_detail = widget.HtmlRow;
    getInfo();
    super.initState();
  }

  @override
  void dispose() {
    // _controller1.dispose();
    super.dispose();
    // _controller.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        _html(),
        coupon != null ? _coupon() : Container(),
        _collage(),
        spec_item_detail != null ? _goods() : Container(),
      ],
    );
  }

  /// 富文本
  Widget _html() {
    if (content_detail['type'] == 'txt') {
      return Html(data: content_detail['contentHTML']);
    } else {
      return Image.network(
        content_detail['url'],
      );
    }
  }

  /// 优惠券
  Widget _coupon() {
    return GestureDetector(
      onTap: () {
        if (kIsWeb) {
          /// 跳转到app失败 进入下载页或者提示系统浏览器打开
          Future.delayed(Duration(seconds: 1), () {
            if (isWechat()) {
              // toast('请在系统浏览器打开本页面');
              // Navigator.of(context).pop();
              setState(() {
                showTip = true;
              });
            } else {
              /// 进入下载页
              webpay(Config.WEB_DOWN_URL +
                  "download.html?is_like=" +
                  arguments['is_like'].toString() +
                  '&likes_num=' +
                  arguments['likes_num'].toString() +
                  '&view_num=' +
                  arguments['view_num'].toString() +
                  '&is_collection=' +
                  arguments['is_collection'].toString() +
                  '&series=' +
                  arguments['series'].toString());
            }
          });
          webpay("yinpinhui://zrhsh.com/app?is_like=" +
              arguments['is_like'].toString() +
              '&likes_num=' +
              arguments['likes_num'].toString() +
              '&view_num=' +
              arguments['view_num'].toString() +
              '&is_collection=' +
              arguments['is_collection'].toString() +
              '&series=' +
              arguments['series'].toString());
        } else {
          if (spec_item_detail == null || spec_item_detail['store'] > 0) {
            Get.offNamed(RouteConfig.collectCouponsCentre);
          }
        }
      },
      child: Visibility(
        visible: coupon != null,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Container(
              width: double.infinity,
              height: 200.w,
              child: Row(children: [
                Expanded(
                  flex: 1,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      RichText(
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          text: TextSpan(children: [
                            TextSpan(
                                text: getconntype(coupon['type_id']),
                                style: TextStyle(
                                    fontSize: 40.w,
                                    fontWeight: EsFontWeights.SemiBold,
                                    color: EsColors.White))
                          ])),
                      // Container(
                      //   padding: EdgeInsets.symmetric(vertical: 0, horizontal: 10),
                      //   decoration: BoxDecoration(color: Color(0xffd32f14), borderRadius: BorderRadius.circular(8)),
                      //   child: Text(
                      //     '满49可用',
                      //     maxLines: 1,
                      //     overflow: TextOverflow.ellipsis,
                      //     style: TextStyle(color: EsColors.White, fontSize: EsSizes.XS, fontWeight: EsFontWeights.Normal),
                      //   ),
                      // )
                    ],
                  ),
                ),
                Expanded(
                    flex: 2,
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Text(
                          coupon['title'],
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                          style: TextStyle(
                              color: EsColors.Money,
                              fontSize: EsSizes.MD,
                              fontWeight: EsFontWeights.SemiBold),
                        ),
                        SizedBox(height: 14),
                        Text(
                          getyearDayFromTimestamp(coupon['use_begin_date']) +
                              '-' +
                              getyearDayFromTimestamp(coupon['use_begin_end']),
                          style: TextStyle(
                              color: EsColors.ContentSecondary,
                              fontSize: EsSizes.XS,
                              fontWeight: EsFontWeights.Normal),
                        ),
                      ],
                    ))
              ]),
              decoration: BoxDecoration(
                  image: DecorationImage(
                      fit: BoxFit.fill,
                      image: AssetImage('assets/images/give_coupons_bg.png'))),
            ),
          ],
        ),
      ),
    );
  }

  ///  拼团活动？？
  Widget _collage() {
    return swichAct(content_detail["bindingGoods"]['activity_type']) != null
        ? GestureDetector(
            onTap: () {
              if (kIsWeb) {
                /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                Future.delayed(Duration(seconds: 1), () {
                  if (isWechat()) {
                    // toast('请在系统浏览器打开本页面');
                    // Navigator.of(context).pop();
                    setState(() {
                      showTip = true;
                    });
                  } else {
                    /// 进入下载页
                    webpay(Config.WEB_DOWN_URL +
                        "download.html?is_like=" +
                        arguments['is_like'].toString() +
                        '&likes_num=' +
                        arguments['likes_num'].toString() +
                        '&view_num=' +
                        arguments['view_num'].toString() +
                        '&is_collection=' +
                        arguments['is_collection'].toString() +
                        '&series=' +
                        arguments['series'].toString());
                  }
                });
                webpay("yinpinhui://zrhsh.com/app?is_like=" +
                    arguments['is_like'].toString() +
                    '&likes_num=' +
                    arguments['likes_num'].toString() +
                    '&view_num=' +
                    arguments['view_num'].toString() +
                    '&is_collection=' +
                    arguments['is_collection'].toString() +
                    '&series=' +
                    arguments['series'].toString());
              } else {
                //if (spec_item_detail['store'] > 0) {//TODO:库存校验
                Get.toNamed(swichAct(
                    content_detail["bindingGoods"]['activity_type'])['router']);
                //}
              }
            },
            child: Container(
              margin: EdgeInsets.only(top: 20.w),
              decoration: BoxDecoration(
                  color: EsColors.Pink,
                  borderRadius:
                      const BorderRadius.all(const Radius.circular(6.0))),
              height: 200.w,
              child: Center(
                child: Text(
                  '${swichAct(content_detail["bindingGoods"]['activity_type'])['name']}${content_detail["bindingGoods"]['activity_name']}',
                  style: TextStyle(color: Colors.white),
                ),
              ),
            ),
          )
        : Container();
  }

  /// 商品
  Widget _goods() {
    return Container(
      margin: EdgeInsets.fromLTRB(20.w, 26.w, 20.w, 0),
      padding: EdgeInsets.all(20.w),
      decoration: EsDecoration.BoxShadowRadius6,
      alignment: Alignment.center,
      child: Row(
        children: [
          GestureDetector(
              onTap: () {
                var itemNumId = spec_item_detail['item_num_id'].toString();
                var styleNumId = spec_item_detail['style_num_id'].toString();
                var shopId = '102002001';
                var ecStyleNumId =
                    spec_item_detail['ec_style_num_id'].toString();
                var typeIndex = spec_item_detail['is_pre_sale'] != null
                    ? spec_item_detail['is_pre_sale']
                    : 0;
                var data = {
                  'itemNumId': itemNumId,
                  'styleNumId': styleNumId,
                  // 'shopId': SpUtil.getInt('storeShopNum').toString(),
                  'shopId': shopId,
                  'ecStyleNumId': ecStyleNumId,
                  'typeIndex': typeIndex,
                };
                Get.toNamed(
                    RouteConfig.goodsDetail +
                        '?itemNumId=$itemNumId&styleNumId=$styleNumId&shopId=$shopId&ecStyleNumId=$ecStyleNumId&typeIndex=$typeIndex',
                    arguments: data);
              },
              child: CachedImage(
                  width: 200.w,
                  height: 200.w,
                  path: '${spec_item_detail['image_default_id']}')),
          SizedBox(width: 24.w),
          Expanded(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisAlignment: MainAxisAlignment.start,
              children: [
                Container(
                    constraints: BoxConstraints(minHeight: 140.w),
                    child: Text(spec_item_detail['item_name'],
                        style: TextStyle(
                            color: EsColors.Title,
                            fontSize: EsSizes.SM * 2.sp,
                            fontWeight: EsFontWeights.Normal))),
                Row(
                  crossAxisAlignment: CrossAxisAlignment.end,
                  children: [
                    Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      mainAxisAlignment: MainAxisAlignment.start,
                      children: [
                        // Text('已抢98765件',
                        //     style: TextStyle(
                        //         color: EsColors.ContentSecondary,
                        //         fontSize: EsSizes.XS * 2.sp,
                        //         fontWeight: EsFontWeights.Normal)),
                        Row(
                          children: [
                            Padding(
                              padding: EdgeInsets.only(top: 4.w, right: 10.w),
                              child: Text('￥${spec_item_detail['price']}',
                                  style: TextStyle(
                                      color: EsColors.Primary,
                                      fontSize: 30.sp,
                                      fontWeight: EsFontWeights.Normal)),
                            ),
                            Text('￥${spec_item_detail['mkt_price']}',
                                style: TextStyle(
                                    decoration: TextDecoration.lineThrough,
                                    color: EsColors.ContentSecondary,
                                    fontSize: 20.sp,
                                    fontWeight: EsFontWeights.Normal)),
                          ],
                        ),
                      ],
                    ),
                    Expanded(child: SizedBox()),
                    GestureDetector(
                      onTap: () {
                        if (kIsWeb) {
                          /// 跳转到app失败 进入下载页或者提示系统浏览器打开
                          Future.delayed(Duration(seconds: 1), () {
                            if (isWechat()) {
                              // toast('请在系统浏览器打开本页面');
                              // Navigator.of(context).pop();
                              setState(() {
                                showTip = true;
                              });
                            } else {
                              /// 进入下载页
                              webpay(Config.WEB_DOWN_URL +
                                  "download.html?is_like=" +
                                  arguments['is_like'].toString() +
                                  '&likes_num=' +
                                  arguments['likes_num'].toString() +
                                  '&view_num=' +
                                  arguments['view_num'].toString() +
                                  '&is_collection=' +
                                  arguments['is_collection'].toString() +
                                  '&series=' +
                                  arguments['series'].toString());
                            }
                          });
                          webpay("yinpinhui://zrhsh.com/app?is_like=" +
                              arguments['is_like'].toString() +
                              '&likes_num=' +
                              arguments['likes_num'].toString() +
                              '&view_num=' +
                              arguments['view_num'].toString() +
                              '&is_collection=' +
                              arguments['is_collection'].toString() +
                              '&series=' +
                              arguments['series'].toString());
                        } else {
                          if (spec_item_detail['store'] > 0) {
                            Get.toNamed(RouteConfig.settleAccounts, arguments: {
                              // 'shop_id': SpUtil.getInt('storeShopNum'),
                              'shop_id': SpUtil.getInt('storeShopNum'),
                              "item_num_id": content_detail["bindingGoods"]
                                  ['goods']['style_num_id'],
                              "style_num_id": content_detail["bindingGoods"]
                                  ['goods']['style_num_id'],
                              "ec_style_num_id": content_detail["bindingGoods"]
                                  ['goods']['style_num_id'],
                              'shopnum': 1
                            });
                          }
                        }

                        print('马上抢');
                      },
                      child: Container(
                        padding: EdgeInsets.symmetric(
                            vertical: 10.w, horizontal: 24.w),
                        child: Text(
                            spec_item_detail['store'] > 0 ? '马上抢' : '已售馨',
                            style: TextStyle(
                                color: EsColors.White,
                                fontSize: EsSizes.MD * 2.sp,
                                fontWeight: EsFontWeights.Medium)),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            ///渐变色
                            colors: [Color(0xffea5504), Color(0xffffbd00)],
                          ),
                          borderRadius: BorderRadius.all(Radius.circular(30.w)),
                        ),
                      ),
                    ),
                  ],
                ),
              ],
            ),
          )
        ],
      ),
    );
  }
}
